﻿using mars_server.csharp.CO;
using mars_server.csharp.VO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace mars_server.csharp.Util
{
    public class JsonUtil
    {
        //通过utf8的编码方式解码bytes -> string
        public static string bytesToStringUTF8(byte[] bytes)
        {
            if (bytes.Length == 0)
            {
                return null;
            }
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            return encoding.GetString(bytes);
        }

        public static string[] splitJsonStr(String JsonStr)
        {
            return JsonStr.Split(new string[] { "$#$#"},StringSplitOptions.RemoveEmptyEntries);
        }
        

        public static List<MessageCO> JsonByteToMessageCO(byte[] bytes)
        {
            if (bytes.Length == 0)
            {
                return null;
            }
            string message = JsonUtil.bytesToStringUTF8(bytes);
            Console.WriteLine(message);
            List<MessageCO> messageCOs = new List<MessageCO>();
            string[] messages = splitJsonStr(message);
            try
            {
                for (int i = 0; i < messages.Length; i++)
                {
                    MessageCO messageCO = (MessageCO)JsonConvert.DeserializeObject(messages[0], typeof(MessageCO));
                    messageCOs.Add(messageCO);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine("[error]【序列化】--------反序列化消息失败!");
                return null;
            }
            return messageCOs;
        }


        public static byte[] ObjToBytesUTF8(Object obj)
        {
            string jsonStr = JsonConvert.SerializeObject(obj);
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            return encoding.GetBytes(jsonStr);
        }


        public static T j2o<T>(Object ob)
        {
            return ((JObject)ob).ToObject<T>();
        }

    }
}
